from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from datetime import timedelta
import io
import base64
from PIL import Image, ImageDraw, ImageFont
from random import randint

from ..database import get_db
from ..models import User
from ..schemas import Token, LoginRequest
from ..utils.security import verify_password, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES, generate_captcha

router = APIRouter(prefix="/api/chance/auth", tags=["authentication"])

# 验证码存储（实际项目中应使用Redis等缓存）
captcha_store = {}

# 生成验证码图片
@router.get("/captcha")
async def get_captcha():
    captcha_key, captcha_text = generate_captcha()
    
    # 创建验证码图片（增大尺寸）
    width, height = 140, 50
    image = Image.new('RGB', (width, height), color=(255, 255, 255))
    draw = ImageDraw.Draw(image)
    
    # 尝试使用系统字体，增大字体大小
    try:
        # 尝试多个常见字体
        font = ImageFont.truetype("arial.ttf", 36)
    except:
        try:
            font = ImageFont.truetype("Arial.ttf", 36)
        except:
            try:
                font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 36)
            except:
                # 如果都找不到，使用默认字体
                font = ImageFont.load_default()
    
    # 绘制验证码文本（居中显示）
    draw.text((15, 5), captcha_text, fill=(0, 0, 0), font=font)
    
    # 绘制干扰线
    for _ in range(5):
        x1 = randint(0, width)
        y1 = randint(0, height)
        x2 = randint(0, width)
        y2 = randint(0, height)
        draw.line([(x1, y1), (x2, y2)], fill=(128, 128, 128), width=1)
    
    # 转换为Base64
    buffer = io.BytesIO()
    image.save(buffer, format="PNG")
    image_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
    
    # 存储验证码（有效期5分钟）
    captcha_store[captcha_key] = captcha_text
    
    return {
        "captcha_key": captcha_key,
        "image": f"data:image/png;base64,{image_str}"
    }

# 用户登录
@router.post("/login", response_model=Token)
async def login(login_data: LoginRequest, db: Session = Depends(get_db)):
    # 验证验证码
    captcha_key = login_data.captcha_key
    captcha_text = login_data.captcha
    
    if captcha_key not in captcha_store or captcha_store[captcha_key] != captcha_text:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="验证码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 移除已使用的验证码
    del captcha_store[captcha_key]
    
    # 验证用户
    user = db.query(User).filter(User.username == login_data.username).first()
    if not user or not verify_password(login_data.password, user.password):
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 创建访问令牌
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    
    return {"access_token": access_token, "token_type": "bearer"}